package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.CourseDao;
import dao.impl.CourseDaoImpl;
import model.Course;

/**
 * Servlet implementation class CourseServlet
 */
@WebServlet("/CourseServlet")
public class CourseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CourseDao cd;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CourseServlet() {
        super();
        // TODO Auto-generated constructor stub
        cd = new CourseDaoImpl();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//解决表单中中文乱码的问题，为了解决写入数据库中乱码的问题，此条语句必须写在第一条哈
		request.setCharacterEncoding("utf-8");
		//通过页面中action参数来决定属于什么操作，然后相应的调用不同的方法
		String action = request.getParameter("action");
		if(action.equals("addCourse")) {
			addCourse(request, response);
		}else if(action.equals("tecCourse")) {
			
		}else if(action.equals("stuCourse")) {
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	//管理员添加课程操作
	protected void addCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String courseName = request.getParameter("course_name");
		String courseHour = request.getParameter("course_hour");
		String courseGrade = request.getParameter("course_grade");
		//通过Course对象来封装页面中的参数
		Course course = new Course();
		course.setCourName(courseName);
		course.setCourHour(Integer.parseInt(courseHour));
		course.setCourCredit(Integer.parseInt(courseGrade));
		HttpSession session = request.getSession();
		//访问DAO层
		if(cd.addCourse(course)) {
			session.setAttribute("list1", cd.queryAllCourse());
			response.sendRedirect("course_list.jsp");
		}else{
			response.sendRedirect("failure.html");
		}
	}
}
